//
//  CJMgmtVC.swift
//  ANOA
//
//  Created by 邱仙凯 on 2022/4/8.
//  Copyright © 2025 aowang. All rights reserved.
//

import UIKit
 
class CJMgmtVC: ProductionBaseController,approvalFlowable {
   
   var dataArray = [CJMgmtModel]()
  
 
      var audit_mark = ""
    var z_record_no = ""
    var z_title = ""
    var contractState = ""

   override func viewDidLoad() {
       super.viewDidLoad()
       self.page = 1
       self.title = "成交管理"
       keyDescription = "单据号"
     

       let appe = KSFilterAppearance()
           .bgHeight(KSGlobal.screenH - 100)
       filterV = KSRaiseUpFilterV(startY:0,appearance: appe, arr: [SlideContent(type: .dateRegion,title: "日期", startDate:startDate,endDate:endDate),SlideContent(type: .singleInput,title: "单据编号", inputStr: z_record_no),SlideContent(type: .singleInput,title: "标题", inputStr: z_title),SlideContent(type: .singleSelect, title: "审核标识",dataArr: ["全部","未提交","已提交","已审核","已退回"].map{ SeString(title: $0, ks_selected: false) },numberOfRow: 3,open: true),SlideContent(type: .singleSelect, title: "合同状态",dataArr: contractSUtil.arr.map{ SeString(title: $0.1, ks_selected: false) },numberOfRow: 3,open: true)])

       
       self.tableView.backgroundColor = Theme.awModuleBgColor
       self.tableView.separatorStyle = .none
       tableView.estimatedRowHeight = 100
       tableView.rowHeight = UITableView.automaticDimension
       tableView.register(GlobalTableViewCell.self, forCellReuseIdentifier: GlobalTableViewCell.identifier)
       tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 100, right: 0)
       
       
       tableView.mj_header = KSRefreshHeader { [unowned self] in
           self.page = 1
           self.network()
       }
       tableView.mj_footer = KSRefreshFooter { [unowned self] in
           self.page+=1
           self.network()
       }
       tableView.mj_header?.beginRefreshing()
       
       navigationItem.rightBarButtonItems = [addItem]

       configFilter()
   }
   func configFilter() {
        
      
       var t1 = inputTypeFilter(nm: "单据号", param: "z_record_no")

       var t2 = inputTypeFilter(nm: "标题", param: "z_title")
    
       var t3 = TemplateModel(JSON:["":""])!
       t3.isFormSHow = "1"
       t3.isFilterShow = "1"
       t3.field_nm = "audit_mark_nm"
       t3.field_annotation = "审核标识"
       t3.field_type = TemplateType.localSelect.rawValue
       t3.select_data = "0:未提交,1:已审核,2:已退回,9:已提交,-1:全部"
       t3.selectDataBack = LocalSelectDataBack(idBack: "audit_mark",nmBack: "audit_mark_nm")
       var t31 = TemplateModel(JSON:["":""])!
       t31.isFormSHow = "0"
       t31.isFilterShow = "0"
       t31.field_nm = "audit_mark"
       t31.field_type = TemplateType.input.rawValue


       var t4 = TemplateModel(JSON:["":""])!
       t4.isFormSHow = "1"
       t4.isFilterShow = "1"
       t4.field_nm = "contractStateNm"
       t4.field_annotation = "合同状态"
       t4.field_type = TemplateType.localSelect.rawValue
       t4.select_data = "0:未生成,1:已生成,:全部"
       t4.selectDataBack = LocalSelectDataBack(idBack: "contractState",nmBack: "contractStateNm")
       var t41 = TemplateModel(JSON:["":""])!
       t41.isFormSHow = "0"
       t41.isFilterShow = "0"
       t41.field_nm = "contractState"
       t41.field_type = TemplateType.input.rawValue
       let temf = [t_begin_dt,t_end_dt,t1,t2,t3,t31,t4,t41]

 
       let yyy = getTopH() + comSearchBanner.ks_height

       self.comSearchBanner.initWithFcontent(startY:yyy,templateFilter: temf)
       self.comSearchBanner.bannerComfirmClo = {
           if let isrefresh = self.tableView.mj_header?.isRefreshing,isrefresh {
               self.tableView.mj_header?.endRefreshing()
               DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) {
                   self.tableView.mj_header?.beginRefreshing()
               }
           }  else {
               self.tableView.mj_header?.beginRefreshing()
           }
       }
  
   }
    
   override func search() {
       self.filterV.confirmClosure = { arr in
           self.startDate = arr[0].startDate
           self.endDate = arr[0].endDate
           self.z_record_no = arr[1].inputStr
           self.z_title = arr[2].inputStr

           let ss = arr[3].dataArr!.filter{ $0.ks_selected }
           if ss.count > 0 {
               self.audit_mark = AuditStatusDesc[ss.first!.title]!
           } else {
               self.audit_mark = ""
           }
           let ss4 = arr[4].dataArr!.filter{ $0.ks_selected }
           if ss4.count > 0 {
               self.contractState = contractSUtil.getK(v: ss4.first!.title)
           } else {
               self.contractState = ""
           }
            self.filterV.close()
           self.tableView.mj_header?.beginRefreshing()
       }
       filterV.present()
       
       
   }
   override func network() {
       self.startDate = any2Str(comSearchBanner.filterV?.filterDic["begin_dt"])
       self.endDate = any2Str(comSearchBanner.filterV?.filterDic["end_dt"])
       self.audit_mark = any2Str(comSearchBanner.filterV?.filterDic["audit_mark"])
       self.contractState = any2Str(comSearchBanner.filterV?.filterDic["contractState"])
       self.z_record_no = any2Str(comSearchBanner.filterV?.filterDic["z_record_no"])
       self.z_title = any2Str(comSearchBanner.filterV?.filterDic["z_title"])

       let dic:[String:String] =  ["z_record_no":z_record_no,"z_title":z_title,"z_zb_no":"","begin_dt":"\(self.startDate)","end_dt":"\(self.endDate)","page":"\(page)","size":"\(KSGlobal.pageSize)","z_audit_mark":self.audit_mark,"z_contract_state":contractState]
        KSNetwork.shared.doRequest(API.homepage(.CJMg_queryAuctionInfo(data: dictionaryToJson(dic))),showHud: false) {  [weak self] (data:BaseResultOK<CJMgmtModel>) in
           guard let `self` = self else {return}
           if data.flag == TRUE {
               if let infos = data.infos {
                   if self.page == 1 {
                       self.dataArray.removeAll()
                   }
                   self.dataArray += infos
                   self.tableView.reloadData()
                   self.tableView.mj_header?.endRefreshing()
                   self.tableView.mj_footer?.endRefreshing()
                   if infos.count < KSGlobal.pageSize {
                       self.tableView.mj_footer?.endRefreshingWithNoMoreData()
                   }
                   
                   
               }
           } else {
               KSToast(data.errorCombine.unwrap)
           }
       }
       
       
       
   }
   override func add() {
       
       
       let view  = CJMgmtForm.initForAdd()
       view.refreshClosure = {
           self.tableView.mj_header?.beginRefreshing()
       }
       self.navigationController?.pushViewController(view, animated: true)
       
   }
   
 
   
   override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
       
       return self.dataArray.count
       
   }
   
   
   override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
       let cell = tableView.dequeueReusableCell(withIdentifier: GlobalTableViewCell.identifier, for: indexPath) as!
       GlobalTableViewCell
       
       let one = dataArray[indexPath.row]
       
       let titleAndStatus = ("\(one.zTitle.unwrap)",one.zAuditMarkName.unwrap)
       var contArr:[(String,String?)]!
        
       contArr = [
            ("成交编号","\(one.zRecordNo.unwrap)"),
            ("商品名称","\(one.zGoodsNm.unwrap)"),
            ("竞拍数量","\(one.zJpCount.unwrap)"),
             ("成交数量","\(one.zCjCount.unwrap)"),
            ("合同状态","\(one.zContractStateNm.unwrap)"),
             ("制单日期","\(one.zCreateTm.unwrap)")

       ]
       if one.zContractStateNm.unwrap == "已生成" {
           cell.setSomeLineColor(line: 4, color: UIColor(kshex:"#32CD32"))
       } else {
           cell.setSomeLineColor(line: 4, color: UIColor(kshex:"#111111"))
       }
       
       
       var btnTitleArr:[String] = []
       
       if one.zAuditMark == "9" {
           btnTitleArr = ["反提交","流程图"]
       } else if one.zAuditMark == "1" {
           btnTitleArr = ["流程图"]
       } else {
           btnTitleArr = ["提交","修改","删除"]
       }
       
       
       cell.setDataSource(contentArr: contArr,btnTitleArr: btnTitleArr,titleAndStatus: titleAndStatus)
       
       
       cell.btnGroupclickAction = {[indexPath,one] tag,titlex in
            
           guard USERINFO.idKey.unwrap ==  self.dataArray[indexPath.row].zStaffId.unwrap else {
               KSToast("非制单人不能做此操作!")
               return
           }
           

           
           if titlex == "提交" {
               
               self.submitNetWork(vc:self,vou_no: one.zRecordNo.unwrap, voc_cd: "CJGG", flow_nm: "CJGGSP", vou_id: one.idKey.unwrap,unitId: one.zOrgId.unwrap, finish: {
                   self.tableView.mj_header?.beginRefreshing()
               })
               
           } else if titlex == "反提交" {
               
               self.resubmitNetWork(vc:self,vou_no: one.zRecordNo.unwrap, voc_cd: "CJGG", flow_nm: "CJGGSP", vou_id: one.idKey.unwrap,unitId: one.zOrgId.unwrap, finish: {
                   self.tableView.mj_header?.beginRefreshing()
               })
    
               
           } else if titlex == "删除" {
               alertUtil(self, title: "确认删除？", operateS: [nameAction(name: "确定", action: { (_) in
                   
                   KSNetwork.shared.doRequest(API.homepage(.CJMg_delAuctionInfo(id_key: one.idKey.unwrap))) { (data:BaseResult<OperateResult>) in
                       if data.flag == TRUE {
                           KSToast("删除成功")
                           self.tableView.mj_header?.beginRefreshing()
                       } else {
                           KSToast(data.errorCombine.unwrap)
                       }
                    }

               })])
           }else if titlex == "修改" {
               let view  = CJMgmtForm.initForView(model: self.dataArray[indexPath.row])
               view.excuteType = .fix
               view.refreshClosure = {
                   self.tableView.mj_header?.beginRefreshing()
               }
               self.navigationController?.pushViewController(view, animated: true)
           } else if titlex == "流程图" {
               // MARK: - 流程图
               if one.newFlow == "0" {
                   TempHelper.shared.viewFlowPic(controller: self, process: "", voc_cd: "CJGG", vou_id: one.idKey.unwrap)

               } else {
                   let oneXX  =  ["查看流程", "voc_cd=${a.voc_cd}&vou_id=${a.id_key}", "0", "flow"]
                   let dicxx  =  ["id_key": "\(one.idKey.unwrap)", "voc_cd": "CJGG"]

                   go2Flow(oneXX: oneXX, chooseUser: [], one: dicxx, vc: self)
               }
           }
       }
       
       
       
       
       return cell
   }
   override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
       let view  = CJMgmtForm.initForView(model: self.dataArray[indexPath.row])
       self.navigationController?.pushViewController(view, animated: true)
       
   }
}
